<template>
  <view class="create-staff">
    <view class="navbar">
      <uni-nav-bar @clickLeft="goback" leftIcon="left" fixed="true" border="false" color="#FFF" statusBar="true"
        backgroundColor="#22b9a3" title="服务人员申请" />
    </view>
    <view class="content">
      <uni-row>
        <uni-col :span="24"> <uni-section type="line" title="申请信息" titleFontSize="35"></uni-section></uni-col>
      </uni-row>

      <uni-forms :modelValue="formData">
        <uni-row>
          <uni-col :span="16" offset=1>
            <uni-forms-item label="姓名" name="name" required>
              <uni-easyinput type="text" v-model="formData.name" placeholder="请填写您的姓名" all />
            </uni-forms-item>
          </uni-col>
        </uni-row>
        <uni-row>
          <uni-col :span="16" offset=1>
            <uni-forms-item label="性别" name="sex" required>
              <uni-data-checkbox v-model="formData.sex" :localdata="sexs" />
            </uni-forms-item>
          </uni-col>
        </uni-row>

        <uni-row>
          <uni-col :span="16" offset=1>
            <uni-forms-item label="手机号" name="phone" required>
              <uni-easyinput type="number" v-model="formData.phone" placeholder="请填写您的手机号" all maxlength="11" />
            </uni-forms-item>
          </uni-col>
        </uni-row>
        <uni-row>
          <uni-col :span="16" offset=1>
            <uni-forms-item label="城市" name="cityCode" required>
              <uni-data-picker @change="fetchCity" placeholder="请选择省份" popup-title="请选择城市" :map="map"
                :localdata="cityList" />
            </uni-forms-item>
          </uni-col>
        </uni-row>
        <uni-row>
          <uni-col :span="16" offset=1>
            <uni-forms-item label="职业选择" name="job" labelWidth="80">
              <view>
                <picker @change="pickerJobChange" :value="index" :range="jobList" range-key="name" mode=selector>
                  <view class="jobinput">{{jobList[index].name}}</view>
                </picker>
              </view>

            </uni-forms-item>
          </uni-col>
        </uni-row>
        <uni-row>
          <uni-col :span="18" offset=1>
            <uni-forms-item label="身份证号码" name="cardNum" required labelWidth="80">
              <uni-easyinput  trim="all" type="idcard" v-model="formData.cardNum" placeholder="请填写您的身份证号码" maxlength="18" />
            </uni-forms-item>
          </uni-col>
        </uni-row>

        <uni-row>
          <uni-col :span="4" offset=1>
            <uni-forms-item label="上传身份证照片" required labelWidth="80">
            </uni-forms-item>
          </uni-col>
        </uni-row>
        <uni-row>
          <uni-col :span="11" offset=1>
            <view class="positive" @tap.prevent="chooseAndUploadIdCard('cardFront')">
              <image v-if='formData.cardFront' :src="formData.cardFront">
              </image>
            </view>
            <progress :percent="frontProcess" activeColor="#22b9a3" stroke-width="3" style="width: 300rpx" />
          </uni-col>
          <uni-col :span="11">
            <view class="reverse" @tap.prevent="chooseAndUploadIdCard('cardReverse')">
              <image v-if='formData.cardReverse' :src="formData.cardReverse">
              </image>
            </view>
            <progress :percent="reverseProcess" activeColor="#22b9a3" stroke-width="3" style="width: 300rpx" />
          </uni-col>
        </uni-row>
        <uni-row>
          <uni-col :span="4" offset=1>
            <uni-forms-item label="个人生活照片" required labelWidth="80">
            </uni-forms-item>
          </uni-col>
        </uni-row>
        <uni-row>
          <uni-col :span="11" offset=1>
            <view class="pic" @tap.prevent="chooseAndUploadIdCard('pic')">
              <image v-if='formData.pic' :src="formData.pic">
              </image>
            </view>
          </uni-col>
        </uni-row>
        <uni-row>
          <uni-col :span="4" offset=1>
            <div class="self">
              <uni-forms-item label="自我介绍" name="brief" required labelWidth="80">
              </uni-forms-item>
            </div>
          </uni-col>
        </uni-row>
        <uni-row>
          <uni-col :span="16" offset=1>
            <textarea v-model="formData.brief" placeholder="请填入自我介绍,不超过100字" maxlength="100" class="selfcontent" />
          </uni-col>
        </uni-row>
      </uni-forms>
      <uni-row>
        <uni-col> <button class="submit" @click="submitForm">提交申请</button></uni-col>
      </uni-row>
    </view>
  </view>
</template>

<script setup>
  import * as http from '@/utils/http'
  import {
    ref,
    onMounted
  } from 'vue'
  const jobList = [{
    id: 1,
    name: '陪诊师'
  }, {
    id: 2,
    name: '护理师'
  }]
  const index = ref(0)
  const formData = ref({
    cardFront: '',
    cardReverse: '',
    pic: '',
    cardNum: null,
    job: 1,
    isEarnest: 2,
    isStart: 2,
    brief: ''
  })
  const sexs = [{
    text: '男',
    value: 1
  }, {
    text: '女',
    value: 2
  }];
  const map = {
    text: 'name',
    value: 'id'
  };
  const cityList = ref([])
  onMounted(async () => {
    const cityResult = await http.getRequest("/peizhen/open-city/getAllCity")
    if (cityResult.code == 0) {
      cityList.value = cityResult.data
    }
  })

  function goback() {
    uni.navigateBack()
  }
  //获取选择的城市
  function fetchCity(e) {
    formData.value.cityCode = e.detail.value[1].value,
      formData.value.city = e.detail.value[1].text
  }

  function pickerJobChange(e) {
    formData.value.job = jobList[e.detail.value].id
    index.value = e.detail.value
  }
  //上传进度
  const frontProcess = ref(0)
  const reverseProcess = ref(0)

  function chooseAndUploadIdCard(type) {
    // 选择身份证正反面照片
    uni.chooseImage({
      count: 1, // 默认为9，设置图片的选择数量
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: (chooseImageRes) => {
        console.log(chooseImageRes);
        let filePath = chooseImageRes.tempFilePaths[0];
        let file = chooseImageRes.tempFiles[0];
        const uploadTask = uni.uploadFile({
          url: http.getHost('/infra/file/upload'), // 你的上传图片的服务器地址
          file: file,
          filePath: filePath,
          name: 'file', // 这里根据后端需要的字段来定义
          formData: {
            'user': 'test' // 其他要传的参数可以在这里添加
          },
          success: (uploadFileRes) => {
            console.log('upload success:', uploadFileRes);
            // 上传成功后的操作
            const result = JSON.parse(uploadFileRes.data)
            if (type == 'cardFront') {
              formData.value.cardFront = result.data
            } else if (type == 'cardReverse') {
              formData.value.cardReverse = result.data
            } else {
              formData.value.pic = result.data
            }
          },
          fail: (uploadFileErr) => {
            console.log('upload fail:', uploadFileErr);
            // 上传失败后的操作
          }
        });
        uploadTask.onProgressUpdate((res) => {
          if (type == 'cardFront') {
            frontProcess.value = res.progress
          } else if (type == 'cardReverse') {
            reverseProcess.value = res.progress
          }
        });
      },
      fail: (chooseImageErr) => {
        console.log('choose fail:', chooseImageErr);
        // 选择失败后的操作
      }
    });
  }

  //提交
  async function submitForm(e) {
    
    if (validateForm()) {
      // 校验通过，执行提交操作  
      const result = await http.postRequest('/peizhen/staff/create', formData.value)
      if (result.code == 0) {
        console.log(result);
        uni.showModal({
          title: '申请信息',
          content: '提交成功,稍后工作人员将会与您联系',
          showCancel: false,
          success: function(res) {
            if (res.confirm) {
              uni.navigateBack()
            }
          }
        })
      } else if (result.code == 1001000010) {
        uni.showModal({
          title: '申请信息',
          content: '您已申请过,请不要重复申请,如有疑问请联系客服',
          showCancel: false,
          success: function(res) {
            if (res.confirm) {
              uni.navigateBack()
            }
          }
        })
      }
    }
  }

  function validateForm() {
    const {
      name,
      phone,
      cityCode,
      cardNum,

    } = formData.value
    // 姓名校验（简单示例，实际可能更复杂）  
    if (!name || name.trim() === '') {
      uni.showToast({
        title: '姓名不能为空',
        icon: 'none'
      });
      return false;
    }

    // 手机号校验  
    if (!/^1[3-9]\d{9}$/.test(phone)) {
      uni.showToast({
        title: '手机号格式不正确',
        icon: 'none'
      });
      return false;
    }

    // 城市校验（简单示例，这里不强制）  
    if (!cityCode) {
      uni.showToast({
        title: '城市不能为空',
        icon: 'none'
      });
      return false;
    }
    // 身份证号码校验  
    if (!/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(cardNum)) {
      uni.showToast({
        title: '身份证号码格式不正确',
        icon: 'none'
      });
      return false;
    }
    return true;
  }
</script>

<style lang="scss">
  .navbar ::v-deep .uni-nav-bar-text {
    font-size: $uni-font-size-title !important;
    font-family: "siyuan";
  }


  .content {
    padding-bottom: 100px;
  }

  .positive,
  .reverse {
    height: 200rpx;
    width: 300rpx;
    background-repeat: no-repeat;
    background-position: center center;
    background-size: cover;

    image {
      height: 200rpx;
      width: 300rpx;
      border-radius: 25rpx;
    }
  }



  .positive {
    background-image: url(http://122.114.92.39:9000/xingyue/system%2F身份正面.png);
  }

  .reverse {
    background-image: url(http://122.114.92.39:9000/xingyue/system%2F身份背面.png);
  }

  .pic {
    height: 200rpx;
    width: 200rpx;
    background-image: url(http://122.114.92.39:9000/xingyue/system/avtor.png);
    background-repeat: no-repeat;
    background-position: center center;
    background-size: cover;

    image {
      height: 200rpx;
      width: 200rpx;
      border-radius: 25rpx;
    }
  }

  .jobinput {
    font-size: 25rpx;
    height: 60rpx;
    line-height: 60rpx;
    border-bottom: solid 1px #f5f5f5;
    text-align: center;
  }

  .self {
    margin-top: 30rpx;
  }

  .selfcontent {
    /* 设置边框样式 */
    border: 1rpx solid #f5f5f5;
    /* 边框宽度、样式和颜色 */
    /* 你可以根据需要添加更多样式 */
    border-radius: 15rpx;
    /* 边框圆角 */
    padding: 10px;
    /* 内边距 */
    height: 100rpx;
    /* 高度 */
    background-color: #e5e5e5;
  }

  .submit {
    margin-top: 50rpx;
    width: 200rpx;
    background-color: #24c373;
    color: white;
    border-radius: 8rpx;
    border: none;
  }
</style>